<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/11/22 0022
 * Time: 13:35
 */

namespace app\index\model;


use think\Model;

class School extends Model
{
    protected $autoWriteTimestamp = "datetime";
    protected $dateFormat = 'Y-m-d H:i:s';

    protected $createTime = "date_entered";
    protected $updateTime = "update_entered";

    public static function init()
    {
        self::event('before_delete', function ($query){
            $school_id = $query->id;
            //判断是否有学生
            $count = Student::where("school_id", "=", $school_id)->count();
            if ($count) {
                return false;
            }
            //判断是否有成绩
            $count = Score::where("school_id", "=", $school_id)->count();
            if ($count) {
                return false;
            }
            return true;
        });
    }

    /**
     * @param int $offset
     * @param int $limit
     * @param array $where
     * @return array
     */
    public function getList($offset = 0, $limit=10, $where = [])
    {
        return $this->where($where)->limit($offset, $limit)->order('id', 'desc')->select()->toArray();
    }

    /**
     * @param array $where
     * @return $this
     */
    public function getListCount($where = [])
    {
        return $this->where($where)->count();
    }

    /**
     * @param $id
     * @return array
     */
    public function getOneById($id)
    {
        return $this->where("id", $id)->findOrEmpty()->toArray();
    }

    /**
     * @param $data
     * @return bool
     */
    public function add($data)
    {
        return $this->save($data);
    }

    /**
     * @param $id
     * @param $data
     * @return bool
     */
    public function edit($id, $data)
    {
        return $this->save($data, [['id', '=', $id]]);
    }

    /**
     *
     * @param $id
     * @return bool
     * @throws \Exception
     */
    public function del($id)
    {
        return self::get($id)->delete();
    }

    public function getAll()
    {
        return $this->selectOrFail();
    }
}